﻿using BrnMall.Core;
using BrnMall.Manager.Domain.Ship;
using BrnMall.Manager.Manager.Ship;
using BrnMall.Services;
using BrnMall.Web.Framework;
using BrnMall.Web.StoreAdmin.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace BrnMall.Web.StoreAdmin.controllers
{
    public class ShipController : BaseStoreAdminController
    {
        /// <summary>
        /// 配送首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            MallUtils.SetAdminRefererCookie(Url.Action("Index"));
            var cashModel = ShipCashManager.GetInfo(WorkContext.StoreId);
            var storeInfo = Stores.GetStoreById(WorkContext.StoreId);

            if (cashModel == null)
                cashModel = new ShipCash() { Cash = "0", ShopState = 0 };

            var model = new ShipIndexModel()
            {
                Cash = cashModel.Cash,
                ShopState = cashModel.ShopState,
                ShopAdress = storeInfo.Address
            };
            return View(model);
        }

        /// <summary>
        /// 申请开通达达
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult Apply(object model)
        {
            var storeInfo = Stores.GetStoreById(WorkContext.StoreId);
            var errMsg = Ships.AddShop(storeInfo, WorkContext.Uid);

            return string.IsNullOrEmpty(errMsg) ? PromptView("开通成功") : PromptView(errMsg);
        }


        #region 充值
        /// <summary>
        /// 配送充值
        /// </summary>
        /// <returns></returns>
        public ActionResult PayIndex()
        {
            return View();
        }

        /// <summary>
        /// 支付确认
        /// </summary>
        /// <param name="OrderMoney">支付金额</param>
        /// <param name="payMode"></param>
        /// <returns></returns>
        public ActionResult PayConfirm(decimal OrderMoney, int payMode = 2)
        {
            var cashInfo = ShipCashManager.GetInfo(WorkContext.StoreId);
            if (cashInfo == null)
                return PromptView("请先开通达达配送");

            return View();
        }

        /// <summary>
        /// 添加充值订单
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="storeId"></param>
        /// <param name="OrderMoney"></param>
        /// <param name="cashItemId"></param>
        /// <returns></returns>
        public ActionResult SubmitOrder(decimal OrderMoney, int payMode = 2)
        {
            var cashInfo = ShipCashManager.GetInfo(WorkContext.StoreId);
            if (cashInfo == null)
                return PromptView("请先开通达达配送");

            var model = GetShipOrder(WorkContext.Uid, WorkContext.StoreId, OrderMoney);

            if (OrderMoney < 0)
                return PromptView("金额不能小于0");

            if (ShipOrderManager.Add(model))
            {
                if (payMode == 1)
                    return Redirect(string.Format("/wechat/ShipPay?oidList={0}&subject=配送充值", model.id));
                else if (payMode == 2)
                    return Redirect(string.Format("/alipay/ShipPay?oidList={0}&subject=配送充值", model.id));
            }

            return PromptView("创建订单失败");
        }


        ShipOrder GetShipOrder(int uid, int storeId, decimal amount)
        {
            ShipOrder model = new ShipOrder()
            {
                Uid = uid,
                StoreId = storeId,
                OrderAmount = amount,
                GiveAmount = 0,
                CreateTime = DateTime.Now
            };
            model.OSN = Orders.GenerateOSN(storeId, uid, 0, DateTime.Now);
            model.OrderState = (int)BrnMall.Core.OrderState.WaitPaying; //等待付款状态
            model.IP = BrnMall.Core.WebHelper.GetIP();
            return model;
        }
        #endregion

        /// <summary>
        /// 配送设置
        /// </summary>
        /// <returns></returns>
        public ActionResult Config()
        {
            MallUtils.SetAdminRefererCookie(Url.Action("Config"));
            var dbModel = ShipConfigManager.GetByStoreId(WorkContext.StoreId);
            ShipConfigModel model = null;
            if (dbModel == null)
            {
                model = new ShipConfigModel();
            }
            else
            {
                model = new ShipConfigModel() { Id = dbModel.Id, IsAutoShip = dbModel.IsAutoShip, MaxDistance = dbModel.MaxDistance, ShipMoney = dbModel.ShipMoney, StoreId = dbModel.StoreId };
            }
            return View(model);
        }

        /// <summary>
        /// 配送设置
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Config(ShipConfigModel model)
        {
            var cashModel = ShipCashManager.GetInfo(WorkContext.StoreId);
            if(cashModel==null|| cashModel.ShopState!=1)
                return PromptView("请先开通达达配送");

            var old = ShipConfigManager.GetByStoreId(WorkContext.StoreId);
            if (old != null)
            {
                old.IsAutoShip = model.IsAutoShip;
                old.MaxDistance = model.MaxDistance;
                old.ShipMoney = model.ShipMoney;
                ShipConfigManager.Update(old);
            }
            else
            {
                var newModel = new Manager.Domain.Ship.ShipConfig() { StoreId = WorkContext.StoreId, IsAutoShip = model.IsAutoShip, MaxDistance = model.MaxDistance, ShipMoney = model.ShipMoney };
                ShipConfigManager.Add(newModel);
            }

            return PromptView("操作成功");
        }

        /// <summary>
        /// 显示商户余额
        /// </summary>
        /// <returns></returns>
        public ActionResult ShipBalance()
        {
            var model = Ships.GetBalance();
            if (model != null)
                ViewData["balance"] = model.deliverBalance;
            else
                ViewData["balance"] = 0;

            return View();
        }


        /// <summary>
        /// 资金流水
        /// </summary>
        /// <returns></returns>
        public ActionResult RecordList(int uid = 0, string accountName = "", int direction = 0, string startTime = "", string endTime = "", int pageNumber = 1, int pageSize = 15)
        {
            accountName = accountName.Trim();
            startTime = string.IsNullOrEmpty(startTime) ? DateTime.Now.AddMonths(-3).ToString("yyyy-MM-dd") : startTime;
            endTime = string.IsNullOrEmpty(endTime) ? DateTime.Now.ToString("yyyy-MM-dd") : endTime;

            if (!SecureHelper.IsSafeSqlString(accountName))
                return PromptView("昵称里含非法关键词，请删除");

            var dbList = ShipRecordManager.GetListPage(WorkContext.StoreId, direction, startTime, endTime, pageNumber, pageSize);

            var model = new ShipRecordListModel()
            {
                uid = uid,
                StartTime = startTime,
                EndTime = endTime,
                List = dbList.Items,
                PageModel = new PageModel(pageSize, pageNumber, (int)dbList.TotalItems),
                Direction = direction
            };
            return View(model);
        }
    }
}